package com.ithinkstudio.jeez.config;

import javax.annotation.Resource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.logout.ForwardLogoutSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutFilter;

import com.ithinkstudio.jeez.config.filter.LoginFilter;
import com.ithinkstudio.jeez.config.filter.TokenFilter;
import com.ithinkstudio.jeez.config.handler.TokenCleanLogoutHandler;

import lombok.extern.slf4j.Slf4j;

/**
 * @description: freemarker配置
 * @author: fengzp
 * @create: 2020/04/21
 */
@Configuration
@Slf4j
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	
	@Resource
	private SecurityProperties securityProperties;
	

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests() //开启登录配置
			.antMatchers(securityProperties.getExcludeUrl().toArray(new String[] {})) //忽略url匹配
			.permitAll()  
			.anyRequest().authenticated() //表示剩余的其他接口，登录之后就能访问
//			.and()
//				.formLogin()
//			
//				.loginPage(securityProperties.getLoginUrl()) //定义登录页面，未登录时，访问一个需要登录之后才能访问的接口，会自动跳转到该页面
//				.loginProcessingUrl("/doLogin") //登录处理接口
//				.successHandler(null) //登录成功的处理器
//				.failureHandler(null) //登录失败的处理器
			.and()
            	.logout()
            	.logoutUrl(securityProperties.getLogoutUrl())  //退出页面
            	.deleteCookies(securityProperties.getTokenHeader())
            	.addLogoutHandler(tokenCleanLogoutHandler())
            	.logoutSuccessHandler(new ForwardLogoutSuccessHandler(securityProperties.getSuccessLogoutForwardUrl())) //退出成功处理器
            .and()
            	.exceptionHandling()
            	.accessDeniedPage(securityProperties.getFailForwardUrl())
            .and()
            	.sessionManagement()
            	.sessionFixation()
            	.migrateSession()
            .and()
            	.csrf().disable()
            	.httpBasic().disable()
            .addFilterAt(tokenFilter(), LogoutFilter.class)
            ;			
			
	}


	@Bean
	public TokenCleanLogoutHandler tokenCleanLogoutHandler() {
		return new TokenCleanLogoutHandler();
	}
	
	@Bean
    public TokenFilter tokenFilter() {
        return new TokenFilter();
    }
	
	@Bean
    public LoginFilter loginFilter() {
        return new LoginFilter(securityProperties.getLoginUrl());
    }

}
